package com.ku.kill.error;

import com.ku.kill.error.BusinessException;
import com.ku.kill.error.EmBusinessError;
import com.ku.kill.response.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: kill2
 * @description: 全局异常处理类
 *
 * ControllerAdvice 有三个功能：
                    全局异常处理
                    全局数据绑定
                    全局数据预处理
 * @author: JokerKu
 * @create: 2020-04-02 16:51
 **/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    //定义ExceptionHandler解决未被controller层吸收的exception
    @ExceptionHandler(Exception.class)//所有异常的父类
    @ResponseStatus(HttpStatus.OK)//将状态码由原来返回的500变成200
    public CommonReturnType HandlerException(HttpServletRequest request, Exception e){
        Map<String,Object> responseData = new HashMap<>();
        if (e instanceof BusinessException){
            BusinessException be = (BusinessException)e;
            responseData.put("errorCode",be.getCode());
            responseData.put("errorMsg",be.getErrorMsg());
            System.out.println("errorMsg："+be.getErrorMsg());
        }else {
            responseData.put("errorCode", EmBusinessError.UNKONMW_ERROR.getCode());
            responseData.put("errorMsg",EmBusinessError.UNKONMW_ERROR.getErrorMsg());
//            responseData.put("errorMsg",e.fillInStackTrace());
        }

        return  CommonReturnType.create(responseData,"fail");
    }
}
